package com.xzit.headline.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.widget.RadioGroup;

import com.xzit.headline.R;
import com.xzit.headline.fragment.HomeFragment;
import com.xzit.headline.fragment.PicFragment;
import com.xzit.headline.fragment.UserFragment;
import com.xzit.headline.fragment.VideoFragment;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.添加点击事件
        listenRadioButtons();
        //2.初始化四个碎片页面
        initPages();
        setContentShowFragment(R.id.home);
    }

    private void setContentShowFragment(int checkedId) {
        Fragment fragment = map.get(checkedId);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.content,fragment);
        transaction.commit();

    }

    private void listenRadioButtons() {
        RadioGroup radioGroup = findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
               setContentShowFragment(checkedId);
            }
        });
    }

    HashMap<Integer, Fragment> map;
    private void initPages() {
        //初始化四个碎片,new出来
        HomeFragment homeFragment = new HomeFragment();
        VideoFragment videoFragment = new VideoFragment();
        PicFragment picFragment = new PicFragment();
        UserFragment userFragment = new UserFragment();

        map = new HashMap<>();
        map.put(R.id.home, homeFragment);
        map.put(R.id.video, videoFragment);
        map.put(R.id.pic, picFragment);
        map.put(R.id.user, userFragment);
    }
}
